/**
 * Sample Skeleton for "Sample.fxml" Controller Class You can copy and paste
 * this code into your favorite IDE
 *
 */
package com.pentofab.payrollmanagement.ui.controller;

import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.util.Callback;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.AttendanceDao;
import com.pentofab.payrollmanagement.dao.EmployeeDao;
import com.pentofab.payrollmanagement.dao.model.Attendance;
import com.pentofab.payrollmanagement.dao.model.AttendanceDetail;
import com.pentofab.payrollmanagement.dao.model.Company;
import com.pentofab.payrollmanagement.dao.model.Employee;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;
import com.pentofab.payrollmanagement.exception.BusinessException;
import com.pentofab.payrollmanagement.exception.ExceptionMsg;
import com.pentofab.payrollmanagement.ui.dialog.DialogFX;
import com.pentofab.payrollmanagement.utilities.Constants;
import com.pentofab.payrollmanagement.utilities.PayRollUtility;

public class AttendanceController extends AbstractUIController implements
		Initializable {
	
	@FXML
	private ChoiceBox<String> loginType;
	@FXML
	private TableView<AttendanceDetail> AttDisp; 
	@FXML
	private TableColumn<AttendanceDetail, String> Comments; 
	@FXML
	private TableColumn<AttendanceDetail, String> Date; 
	@FXML
	private TableColumn<AttendanceDetail, String> InTime; 
	@FXML
	private TableColumn<AttendanceDetail, String> LogOutTime; 
/*	@FXML
	private TableColumn<AttendanceDetail, String> RowNo; */
	@FXML
	private Button Reset; 
	@FXML
	private AnchorPane Root; 
	@FXML
	private Button save; 
	@FXML
	private Button cancel; 
	@FXML
	private TextField eIdLabel; 
	@FXML
	private ComboBox<String> enameDD; 
	@FXML
	private GridPane grid; 
	@FXML
	private ComboBox<String> logOutTimeDD; 
	@FXML
	private ComboBox<String> loginTimeDD; 
	/*@FXML
	private Button modify;*/ 
	@FXML
	private TextField statusLabel; 
	private Company company ;
	

	private EmployeeDao employeeMgmt = PayrollApplicationFactory.getEmployeeMgmt();
	private AttendanceDao attandeanceMgmt = PayrollApplicationFactory.getAttandanceMgmt();

	private List<String> empNameList = null;
	private String preferabelname = "";
	private Employee employeeToAttandance = null;
	private Attendance latestAttEntry = null;
	private boolean isLogOutTimeEmpty = false;
	private ArrayList<Attendance> attInfoList = null;

	final private ObservableList<AttendanceDetail> data = FXCollections
			.observableArrayList();
	private UserAccounts userAccounts;

	@Override
	// This method is called by the FXMLLoader when initialization is complete
	public void initialize(URL fxmlFileLocation, ResourceBundle resources) {

		init();
	}

	public void init() {

		initilizeTablePros();
		save.setDisable(true);
//		modify.setDisable(true);
		loginTimeDD.getItems().addAll(populateLoginLogOutTIme());
		logOutTimeDD.getItems().addAll(populateLoginLogOutTIme());
		eidLableFocusHandler();
		loginTimeCBoxFocusHandler();
		loOutTimeCBoxFocusHandler();
		statusLabel.setEditable(false);
		statusLabel.setFocusTraversable(false);
		loginTimeDD.setEditable(false);
		loginTimeDD.setDisable(true);
		loginTimeDD.setFocusTraversable(false);
		logOutTimeDD.setEditable(false);
		logOutTimeDD.setDisable(true);
		logOutTimeDD.setFocusTraversable(false);
		moveFocusToComp(loginType);
	}

	// Handler for Button[fx:id="Reset"] onMouseClicked
	// Handler for Button[fx:id="Save"] onMouseClicked
	// Handler for Button[fx:id="cancel"] onMouseClicked
	// Handler for Button[fx:id="modify"] onMouseClicked
	public void handleButtonAction(Event event) {
		// handle the event here
		String source = ((Button) event.getSource()).getId();
		PayRollUtility.debug("event : " + source);
		if (event instanceof MouseEvent) {
			PayRollUtility.debug("Mouse event");

			if (source.equals("save")) {
				PayRollUtility.debug("save");
				saveAttandanceEntry();
			}/* else if (source.equals("modify")) {
				modifyAttandance();
			} */else if (source.equals("cancel")) {
				goBack();
			} else if (source.equals("reset")) {

				refreshUI(company,userAccounts);
			}
		} else if (event instanceof KeyEvent) {

			KeyEvent keyEvent = (KeyEvent) event;
			KeyCode keyCode = keyEvent.getCode();
			if (keyCode == keyCode.ENTER) {

				if (source.equals("save")) {
					PayRollUtility.debug("save");
					saveAttandanceEntry();
				} /*else if (source.equals("modify")) {

					modifyAttandance();
				}*/ else if (source.equals("cancel")) {
					goBack();
				} else if (source.equals("reset")) {
					refreshUI(company,userAccounts);
				}

			}
		}

	}

	public void eidLableFocusHandler() {

		eIdLabel.focusedProperty().addListener(new ChangeListener<Boolean>() {
			@Override
			public void changed(ObservableValue<? extends Boolean> ov,
					Boolean lostFocus, Boolean getFocus) {
				
				PayRollUtility
						.debug("============== eidLableFocusHandler Start========================");
				if (lostFocus) {
					try {
						String empId = eIdLabel.getText().trim();
						if (!empId.equals("")) {
							PayRollUtility.validateEmpId(empId);
							employeeToAttandance = employeeMgmt.getEmpById(empId);
							populateAttForm(empId);
						}
					} catch (Exception exception) {
						eIdLabel.deselect();
						eIdLabel.clear();
						exception.printStackTrace();
						DialogFX.errorDialog(exception.getMessage());
						moveFocusToComp(loginType);
					}
				}
				PayRollUtility
						.debug("============== eidLableFocusHandler END========================");
			}
		});
	}

	// Called every time when combo box is changed
	@FXML
	private void handleEnameComboBoxAction(KeyEvent event) {

		PayRollUtility
				.debug("===========  handleComboBoxAction start ================");
		String current = enameDD.getEditor().getText().trim();
		current = current + " ";
		KeyCode keyCode = event.getCode();
		PayRollUtility.debug("keyCode : " + keyCode);
		try {
			if (keyCode == KeyCode.DELETE) {
				System.out.println("text cleared");
				enameDD.getEditor().clear();
				enameDD.getItems().removeAll(enameDD.getItems());
			} else if (keyCode == KeyCode.BACK_SPACE) {
				enameDD.getEditor().deletePreviousChar();
				if (current.length() <= 3) {
					enameDD.getItems().removeAll(enameDD.getItems());
				}
			} else if (current.length() > 3
					&& keyCode.getName().matches("[A-za-z]")) {
				current = enameDD.getEditor().getText().trim();
				System.out.println("San : " + current);
				empNameList = 
				PayRollUtility.getAllEmpName(employeeMgmt
				 .getEmpByName("SA",current, Constants.like));
				enameDD.setItems(FXCollections.observableArrayList(empNameList));
				enameDD.show();
				System.out.println("preferabelname in combo : "
						+ preferabelname);
			} else if (keyCode == KeyCode.TAB || keyCode == KeyCode.ENTER) {
				processEnameFormCBox();
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			enameDD.getEditor().deselect();
			enameDD.getEditor().clear();
			enameDD.getItems().removeAll(enameDD.getItems());
			DialogFX.errorDialog(exception.getMessage());
//			moveFocusToComp(enameDD);
		}
		PayRollUtility
				.debug("===========  handleComboBoxAction end ================");
	}

	private void processEnameFormCBox() {

		PayRollUtility
				.debug("================= eNameCBoxFocusHandler start====================");
		preferabelname = enameDD.getEditor().getText();
		PayRollUtility.debug("preferabelname : " + preferabelname);
		try {

			if (enameDD.isFocusTraversable()
					&& (preferabelname == null || preferabelname.equals(""))) {
				DialogFX.infoDialog(ExceptionMsg.EMP_NAME_ID_EMPTY);
				moveFocusToComp(eIdLabel);
				return;
			}

			if (enameDD.isFocusTraversable() && preferabelname.length() > 2) {

				ArrayList<Employee> employeeList = 
				employeeMgmt.getEmpByName("SA",
				preferabelname, Constants.equals);
				if (employeeList.size() > 1) {

					DialogFX.infoDialog(ExceptionMsg.FOUND_MORE_THAN_ONE_EMP_WITH_NAME
							+ preferabelname + ExceptionMsg.PLEASE_USE_EMP_ID);
					enameDD.getItems().removeAll(enameDD.getItems());
					enameDD.getSelectionModel().select("");
					moveFocusToComp(eIdLabel);
					return;

				} else {
					employeeToAttandance = employeeList.get(0);
				}
				String empId = employeeToAttandance.getEmpId();
				PayRollUtility.debug("Populate EID from ENAME : " + empId);
				if (!empId.trim().equals("")) {

					populateAttForm(empId);
				}

				if (loginTimeDD.isFocusTraversable()) {
					moveFocusToComp(loginTimeDD);
				} else {
					moveFocusToComp(logOutTimeDD);
				}
			}
		} catch (BusinessException exception) {

			exception.printStackTrace();
			enameDD.getEditor().deselect();
			enameDD.getEditor().clear();
			enameDD.getItems().removeAll(enameDD.getItems());
			DialogFX.errorDialog(exception.getMessage());
//			moveFocusToComp(enameDD);

		}
		PayRollUtility
				.debug("================= eNameCBoxFocusHandler end====================");
	}

	private void loginTimeCBoxFocusHandler() {

		PayRollUtility
				.debug("=============loginTimeCBoxFocusHandler start=========================");
		loginTimeDD.focusedProperty().addListener(
				new ChangeListener<Boolean>() {
					@Override
					public void changed(ObservableValue<? extends Boolean> ov,
							Boolean lostFocus, Boolean getFocus) {
						if (getFocus && loginTimeDD.isFocusTraversable()) {
							if (eIdLabel.getText().trim().equals("")
									&& enameDD.getEditor().getText().trim()
											.equals("")) {
								DialogFX.infoDialog(ExceptionMsg.EMP_NAME_ID_EMPTY);
								moveFocusToComp(eIdLabel);
							}
						}
					}
				});

		PayRollUtility
				.debug("=============loginTimeCBoxFocusHandler end=========================");
	}

	private void loOutTimeCBoxFocusHandler() {

		PayRollUtility
				.debug("=============loOutTimeCBoxFocusHandler start=========================");
		logOutTimeDD.focusedProperty().addListener(
				new ChangeListener<Boolean>() {
					@Override
					public void changed(ObservableValue<? extends Boolean> ov,
							Boolean lostFocus, Boolean getFocus) {

						if (getFocus && logOutTimeDD.isFocusTraversable()) {
							if (eIdLabel.getText().trim().equals("")
									&& enameDD.getEditor().getText().trim()
											.equals("")) {
								DialogFX.infoDialog(ExceptionMsg.EMP_NAME_ID_EMPTY);
								moveFocusToComp(eIdLabel);
							}
						}

					}
				});
		PayRollUtility
				.debug("=============loOutTimeCBoxFocusHandler end=========================");
	}

	private void initilizeTablePros() {
		Date.setSortType(TableColumn.SortType.ASCENDING);
//		RowNo.setSortType(TableColumn.SortType.ASCENDING);
		LogOutTime.setSortable(false);
		InTime.setSortable(false);
		Comments.setSortable(false);

		// TODO : Will be set based on Logged in employee credential
		if (true) {
			Callback<TableColumn<AttendanceDetail, String>, TableCell<AttendanceDetail, String>> callback = TextFieldTableCell
					.forTableColumn();

			Comments.setCellFactory(callback);
			Comments.setOnEditCommit(new EventHandler<CellEditEvent<AttendanceDetail, String>>() {
				public void handle(CellEditEvent<AttendanceDetail, String> parm) {
					disableAttandanceForm();
					parm.getTableView().getItems()
							.get(parm.getTablePosition().getRow())
							.setComments(parm.getNewValue());
				}
			});

			InTime.setCellFactory(callback);
			InTime.setOnEditCommit(new EventHandler<CellEditEvent<AttendanceDetail, String>>() {
				public void handle(CellEditEvent<AttendanceDetail, String> parm) {
					disableAttandanceForm();
					parm.getTableView().getItems()
							.get(parm.getTablePosition().getRow())
							.setInTime(parm.getNewValue());
				}
			});

			LogOutTime.setCellFactory(callback);
			LogOutTime
					.setOnEditCommit(new EventHandler<CellEditEvent<AttendanceDetail, String>>() {
						public void handle(
								CellEditEvent<AttendanceDetail, String> parm) {
							disableAttandanceForm();
							parm.getTableView().getItems()
									.get(parm.getTablePosition().getRow())
									.setLogOutTime(parm.getNewValue());
						}
					});

			Date.setCellFactory(callback);
			Date.setOnEditCommit(new EventHandler<CellEditEvent<AttendanceDetail, String>>() {
				public void handle(CellEditEvent<AttendanceDetail, String> parm) {
					disableAttandanceForm();
					parm.getTableView().getItems()
							.get(parm.getTablePosition().getRow())
							.setComments(parm.getNewValue());
				}
			});
		}
	}

	private void resetAttandanceForm() {
		
		empNameList = null;
		preferabelname = null;
		employeeToAttandance = null;
		latestAttEntry = null;
		isLogOutTimeEmpty = false;
		attInfoList = null;
		
		loginType.getSelectionModel().clearSelection();
		eIdLabel.setDisable(false);
		eIdLabel.clear();
		eIdLabel.setFocusTraversable(true);
		eIdLabel.setEditable(true);

		enameDD.setDisable(false);
		enameDD.setEditable(false);
		enameDD.getSelectionModel().select("");
		enameDD.getItems().removeAll(enameDD.getItems());
		enameDD.setFocusTraversable(false);
		enameDD.getEditor().clear();

		loginTimeDD.setDisable(false);
		loginTimeDD.setEditable(true);
		loginTimeDD.getSelectionModel().select("");
		loginTimeDD.getItems().removeAll(loginTimeDD.getItems());
		loginTimeDD.getItems().addAll(populateLoginLogOutTIme());
		loginTimeDD.setFocusTraversable(false);
		loginTimeDD.setDisable(true);

		logOutTimeDD.setDisable(false);
		logOutTimeDD.setEditable(true);
		logOutTimeDD.getSelectionModel().select("");
		logOutTimeDD.getItems().removeAll(logOutTimeDD.getItems());
		logOutTimeDD.setPromptText("");
		logOutTimeDD.getItems().addAll(populateLoginLogOutTIme());
		logOutTimeDD.setFocusTraversable(false);
		logOutTimeDD.setDisable(true);

		statusLabel.setText("");
//		statusLabel.setDisable(true);

		data.removeAll(data);
		AttDisp.setItems(data);

		moveFocusToComp(loginType);
		
		if(employeeToAttandance != null){
			
			eIdLabel.setText(employeeToAttandance.getEmpId());
			eIdLabel.setEditable(false);
		}

	}

	private ArrayList<String> populateLoginLogOutTIme() {

		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		System.out.println("hour : "+hour);
		int minutes = calendar.get(Calendar.MINUTE);

		if (minutes > 15 && minutes < 45) {
			
			calendar.set(Calendar.MINUTE, 30);
		} else {
			
			if (minutes < 15)
				calendar.set(Calendar.MINUTE, 00);
			if (minutes > 45) {

				calendar.set(Calendar.HOUR_OF_DAY, hour + 1);
				calendar.set(Calendar.MINUTE, 00);
			}
		}
		ArrayList<String> timeList = new ArrayList<String>();

		timeList.add(changeHrs(calendar, -60));
		timeList.add(changeHrs(calendar, -30));
		timeList.add(changeHrs(calendar, 00));
		timeList.add(changeHrs(calendar, 30));
		timeList.add(changeHrs(calendar, 60));
		PayRollUtility.debug("timeList : " + timeList);
		return timeList;
	}

	private String changeHrs(Calendar calendar, int time) {
		calendar = (Calendar) calendar.clone();
		calendar.add(Calendar.MINUTE, time);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minutes = calendar.get(Calendar.MINUTE);
		return hour + ":" + minutes;

	}

	/*
	 * private <T> void filterItems(String filter, ComboBox<T> comboBox, List
	 * items) { List filteredItems = new ArrayList(); for (int
	 * i=0;i<items.size();i++) { if
	 * (items.get(i).toString().toLowerCase().startsWith(filter.toLowerCase()))
	 * { filteredItems.add(items.get(i)); } }
	 * comboBox.setItems(FXCollections.observableArrayList(filteredItems)); }
	 */

	private void populateAttTable(ArrayList<Attendance> attInfo) {

		PayRollUtility
				.debug("===================== populateAttTable start =====================");
		/*RowNo.setCellValueFactory(new PropertyValueFactory<AttendanceDetail, String>(
				"RowNo"));*/

		Date.setCellValueFactory(new PropertyValueFactory<AttendanceDetail, String>(
				"Date"));

		InTime.setCellValueFactory(new PropertyValueFactory<AttendanceDetail, String>(
				"InTime"));

		LogOutTime
				.setCellValueFactory(new PropertyValueFactory<AttendanceDetail, String>(
						"LogOutTime"));

		Comments.setCellValueFactory(new PropertyValueFactory<AttendanceDetail, String>(
				"Comments"));
		data.removeAll(AttDisp.getItems());
		if(attInfo != null)
		data.addAll(AttendanceDetail.getAttandanceDetailList(attInfo));
		PayRollUtility.debug("data  : " + data);
		AttDisp.setItems(data);
		
		int status = 0;
		if(attInfo!=null && attInfo.size() > 0 ){
			
			
			Iterator<Attendance> attIterator = attInfo.listIterator();
			while(attIterator.hasNext()){
				Attendance att = attIterator.next();
				
				if(!att.getLoginTime().equals("") && !att.getLogoutTime().equals("")){
					
				/*	if(att.getLogoutTime().equals("")){
						String loginTIme = att.getLoginTime();
						String[] time = loginTIme.split(":");
						int hrs = Integer.parseInt(time[0]);
						int mins = Integer.parseInt(time[1]);
						
						Calendar cal = Calendar.getInstance();
						int hr = cal.get(Calendar.HOUR_OF_DAY);
						int min = cal.get(Calendar.MINUTE);
						
						status = status+(hr - hrs)*60+  min - mins;
						
					}else{*/
						String loginTIme = att.getLoginTime();
						String[] time = loginTIme.split(":");
						int hrs = Integer.parseInt(time[0]);
						int mins = Integer.parseInt(time[1]);
						
						String logOut = att.getLogoutTime();
						String[] OutTime = logOut.split(":");
						int outHrs = Integer.parseInt(OutTime[0]);
						int outMins = Integer.parseInt(OutTime[1]);
						if(hrs > outHrs){
							outHrs = outHrs+24;
						}
						
						status = status+(outHrs - hrs)*60+  outMins - mins;
					/*}*/
					
				}
			}
			
		}
		
		String computedStatus = status/60+":"+status%60;
		statusLabel.setText(computedStatus);
		
		PayRollUtility
				.debug("===================== populateAttTable end =====================");

	}

	public void populateAttForm(String empId) throws BusinessException {

		PayRollUtility
				.debug("============= populateAttForm Start ================");
		if(loginType.getSelectionModel().getSelectedIndex() < 0){
			
			showInfo(UIMessages.PLEASE_SELECT_LOGIN_TYPE);
			moveFocusToComp(loginType);
			return;
		}else if(loginType.getSelectionModel().getSelectedIndex() == 2){
			
			attInfoList = attandeanceMgmt.getAttandaceInfo(empId,null);
			
			if(attInfoList != null)
				latestAttEntry = attInfoList.get(attInfoList.size() - 1);
			
			if (latestAttEntry!= null && !latestAttEntry.getLoginTime().equals("")
					&& latestAttEntry.getLogoutTime().equals("")) {
				
				attInfoList = null;
				latestAttEntry = null;
				showError(UIMessages.LAST_LOG_OUT_TIME_NOT_SET);
				loginType.getSelectionModel().clearSelection();
				moveFocusToComp(loginType);
				return;
			}
			
			if(latestAttEntry != null){
				
				if(showConfirmDialog(String.format(UIMessages.CONFIRM_LAST_LOGOUT,empId))){
					attandeanceMgmt.updateLogOutStatus(empId,latestAttEntry.getDate(),true);
					latestAttEntry = null;
				}else{
					showInfo(UIMessages.PLEASE_SELECT_LOGIN_TYPE);
					moveFocusToComp(loginType);
					return;
				}
			}
		}
		save.setDisable(false);
//		modify.setDisable(false);
		String empName = employeeToAttandance.getEmpName();

		eIdLabel.setText(empId);
		eIdLabel.setEditable(false);
		eIdLabel.setFocusTraversable(false);

		enameDD.getSelectionModel().select(empName);
		// enameDD.setEditable(false);
		enameDD.setFocusTraversable(false);
		enameDD.setDisable(true);

		attInfoList = attandeanceMgmt.getAttandaceInfo(empId,null);
		

		if (attInfoList != null) {
			
			populateAttTable(attInfoList);
			latestAttEntry = attInfoList.get(attInfoList.size() - 1);
			

			if (!latestAttEntry.getLoginTime().equals("")
					&& latestAttEntry.getLogoutTime().equals("")) {
				
				loginTimeDD.getItems().add(latestAttEntry.getLoginTime());
				loginTimeDD.getSelectionModel().select(
						latestAttEntry.getLoginTime());
				logOutTimeDD.setDisable(false);
				logOutTimeDD.setEditable(true);
				logOutTimeDD.setFocusTraversable(true);
				isLogOutTimeEmpty = true;
			} else {
				loginTimeDD.setDisable(false);
				loginTimeDD.setEditable(true);
				loginTimeDD.setFocusTraversable(true);
				isLogOutTimeEmpty = false;
			}
		} else {
			
			loginTimeDD.setDisable(false);
			loginTimeDD.setEditable(true);
			loginTimeDD.setFocusTraversable(true);
		}
		PayRollUtility
				.debug("============= populateAttForm END ================");
	}

	private void disableAttandanceForm() {

		eIdLabel.setDisable(true);
		eIdLabel.setFocusTraversable(false);
		enameDD.setDisable(true);
		enameDD.setFocusTraversable(false);
		save.setDisable(true);
		save.setFocusTraversable(false);
		statusLabel.setFocusTraversable(false);
		loginTimeDD.setDisable(false);
		loginTimeDD.getEditor().clear();
		loginTimeDD.setEditable(false);
		loginTimeDD.setFocusTraversable(false);
		loginTimeDD.setDisable(true);

		loginTimeDD.setDisable(false);
		loginTimeDD.getEditor().clear();
		loginTimeDD.setEditable(false);
		loginTimeDD.setFocusTraversable(false);
		loginTimeDD.setDisable(true);

	}

	// Called when the save button is clicked
	private void saveAttandanceEntry() {
		PayRollUtility
				.debug("===================== saveAttandanceEntry start =====================");
		String empId = employeeToAttandance.getEmpId();
		
		System.out.println("latestAttEntry : "+latestAttEntry);
		
//		modify.setDisable(true);
		if (isLogOutTimeEmpty) {
			try {
				
				String logOutTime = logOutTimeDD.getEditor().getText();
				logOutTime =logOutTime.replace(".", ":");
				
				if(!logOutTime.matches("[0-9]{1,2}:[0-9]{1,2}")){
					showError("Invlid logOut Time, Please enter time in XX:YY or XX.YY format");
					return;
				}
				
				latestAttEntry.setLogoutTime(logOutTime);
				attandeanceMgmt.setlogOutTime(latestAttEntry);
				attInfoList = attandeanceMgmt.getAttandaceInfo(empId, null);
				populateAttTable(attInfoList);
				save.setDisable(true);
				eIdLabel.setDisable(true);
			} catch (BusinessException exception) {
				logOutTimeDD.getEditor().clear();
				exception.printStackTrace();
				DialogFX.errorDialog(exception.getMessage());
				moveFocusToComp(logOutTimeDD);
			}
		} else {
			try {
				
				Date date = (latestAttEntry == null ) ? new Date() : PayRollUtility.convertStringToDate(latestAttEntry.getDate());
				int rownum =1;
				if(latestAttEntry != null){
					rownum = latestAttEntry.getRownumber()+1;
				}
				String loginTime = loginTimeDD.getSelectionModel().getSelectedItem();
				
				loginTime = loginTime.replace(".", ":");
				
				if((!loginTime.matches("[0-9]{1,2}:[0-9]{1,2}"))){
					showError("Invlid login Time, Please enter time in XX:YY or XX.YY format");
					return;
				}
				String logOutTime = "";
				String createdEmp = userAccounts.getUsername();
				attandeanceMgmt.addAttandeanceEntry(empId, date, loginTime,
						logOutTime, createdEmp,rownum,(rownum==1),false);
				attInfoList = attandeanceMgmt.getAttandaceInfo(empId, null);
				populateAttTable(attInfoList);
				save.setDisable(true);
				eIdLabel.setDisable(true);
			} catch (Exception exception) {

				loginTimeDD.getEditor().clear();
				exception.printStackTrace();
				showError(exception.getMessage());
				moveFocusToComp(loginTimeDD);
			}
		}

		PayRollUtility
				.debug("===================== saveAttandanceEntry end =====================");
	}


	@Override
	public Parent getView() {
		return Root;
	}

	@Override
	public String getTitle() {
		return UIMessages.UITitles.ATTENDANCE;
	}

	public void refreshUI(Object... args) {
		
		eIdLabel.setDisable(false);
		if(args != null && args.length > 0){
			
			company = (Company)args[0];
			if(args.length > 1 && args[1] instanceof UserAccounts){
				userAccounts = (UserAccounts)args[1];
			}
			if(args.length > 2 && args[2] instanceof Employee){
				employeeToAttandance =(Employee) args[2];
			}
		
		}
		resetAttandanceForm();
	}
	
	public void goBack() {
		if (getParent() != null && getParent().length() > 0) {
			PayrollApplicationFactory.getMainController().showScreen(
					getParent(), false);
		}
	}
}